<?php
namespace jy_baojfee;
defined('BY_JYA') or exit('error');
/*
	分红插件会员类
	如果将加盟商各项数据在每次数据变动时计算好并存入数据库。
	那么分别需要做
		在设置上下级关系时，修改新上级的 下线数量、加盟商数量、订单数量、订单佣金数量等数据
		在变更上下级关系时，修改原、新上级的各项参数
		在发生订单时，修改上级的订单相关参数
		在用户成为加盟商时，修改上级的加盟商数量相关数据
*/
class member extends \plugin{
	/*
		核实加盟商,$isset无条件成为加盟商
	*/
	public function checkmember($mid=0,$isexi=false,$isset=false){
			$mid=$mid?:$_SESSION['uid'];
			$member=$this->get('member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));			
			$page_setting=$this->plugin_setting('page_setting');
			$page_setting['tagent']=$page_setting['tagent']?:'代理商';
			if(!$member['mid']){
				$this->register(array('mid'=>$mid));
				$member=$this->get('member',array('mid'=>$mid));
			}
			if(!$member['is_agent']){
				//如果成为加盟商无条件，此处自动申请成为加盟商
				if($this->setting['become']==0 || $isset || ($this->setting['become']==5 && $this->session('becomefromuser'))){
					//加盟商无需审核，此处自动审核
					$ispass=true;
					$this->apply_agent($member['mid']);
					if($this->setting['become_check'] && $isexi){
						exi('申请正在审核请耐心等待！','error','jy_baojfee/apply/');
					}elseif($isset){
						return true;
					}
				}elseif($this->setting['become']==2){
					//消费次数
					$buynums=pdo_count('jy_weishop_order',array('ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'id');
					if($buynums>=$this->setting['num']){
						$ispass=true;
						$this->apply_agent($member['mid']);
						if($this->setting['become_check'] && $isexi){
							exi('申请正在审核请耐心等待。','error','jy_baojfee/apply/');
						}
					}elseif($isexi){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_baojfee/apply/');
					}
				}elseif($this->setting['become']==3){
					//消费金额
					$buyfee=pdo_getsum('jy_weishop_order',array('ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'price');
					if($buyfee>=$this->setting['money']){
						$ispass=true;
						$this->apply_agent($member['mid']);
						if($this->setting['become_check'] && $isexi){
							exi('申请正在审核请耐心等待。','error','jy_baojfee/apply/');
						}
					}elseif($isexi){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_baojfee/apply/');
					}
				}elseif($this->setting['become']==4){
					//购买指定商品
					$become_goods=$this->setting['become_goods'];
					foreach($become_goods as &$bgv){
						$isbuy=pdo_count('jy_weishop_order_goods',array('mid'=>$member['mid'],'goodsid'=>$bgv['id'],'ispay'=>1),'id');
						if($isbuy>0){
							$ispass=true;
							$this->apply_agent($member['mid']);
							break;
						}
					}
					if($this->setting['become_check'] && $isexi && $ispass){
						exi('您的申请，正在审核请耐心等待！','error','jy_baojfee/apply/');
					}elseif($isexi && !$ispass){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_baojfee/apply/');
					}
				}else{
					if($isexi){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_baojfee/apply/');
					}
				}
				if($ispass && $isexi){
					exi('','','jy_baojfee/index/');
				}
			}elseif($member['stop'] && $isexi){
				if($isset){
					return true;
				}
				exi('你的'.$page_setting['tagent'].'身份已禁用！','error','jy_baojfee/apply/');
			}elseif((!$member['realname'] || !$member['mobile']) && $isexi){
				if($isset){
					return true;
				}
				if($this->setting['become_reg']==1){
					exi('请先完善信息','error','jy_baojfee/info/');
				}else{
					
				}
			}
			return $member;
	}
	public function checklogin(){
		if(!$_SESSION['uid']){
			exi('','','jy_baojfee/login/');
		}
		return true;
	}
	public function member_update($mid,$update=array()){
		pdo_update('jy_baojfee_member',$update,array('mid'=>$mid));
		return true;
	}
	/*
		会员注册
	*/
	public function register($member=array()){
		if(!$member['uniacid']){
			$member['uniacid']=$_SESSION['uniacid'];
		}
		if(!$member['mid']){
			$member['mid']=$_SESSION['uid'];
		}		
		if(!$member['createtime']){
			$member['createtime']=TIMESTAMP;
		}
		if(!$member['mid']){
			return error('加盟商会员注册失败，缺少会员ID.');
		}
		$ismid=$this->get('member',array('mid'=>$member['mid']),array('mid'));
		if($ismid){
			return false;
		}
		$this->insert('member',$member);
		if($member['agent_id']){
			$this->set_parent($member['mid'],$member['agent_id']);
		}
		if(!$member['agent_id'] && $_SESSION['this']=='custom' && ($this->setting['become_child']==1 || $this->setting['become_child']==4)){
			$agent_id=pdo_getcolumn('core_members',array('id'=>$_SESSION['uid']),'fromuser');
			$agent_id=$agent_id?:$_SESSION['fromuser'];
			if($agent_id){
				$this->set_parent($member['mid'],$agent_id);
                $member['agent_id']=$agent_id;
			}
		}
		//如果成为加盟商无条件，此处自动申请成为加盟商
		if($this->setting['become']==0 || $this->session('becomefromuser')){
			//加盟商无需审核，此处自动审核
			$this->apply_agent($member['mid'],true);
		}
        return $member;
	}
	/*
		设置上下级关系
	*/
	public function set_parent($mid=0,$parent_id=0,$ischange=false){
		$mid=$mid?:$_SESSION['uid'];
		$member=$this->get('member',array('mid'=>$mid),array('mid','is_agent','level_id','agent_id','createtime'));
		$old_agent_id=$member['agent_id'];
		$isuser=pdo_getcolumn('core_members',array('id'=>$parent_id),'id');
		//如果不存在该会员，已经是加盟商或已经有上级了，取消执行。
		if(($old_agent_id || !$isuser || ($member['is_agent'] && $member['createtime']+60<TIMESTAMP)) && !$ischange){
			return true;
		}
		//如果他的上级是我
		$ta_agent_id=$this->getcolumn('member',array('mid'=>$parent_id),'agent_id');
		if($ta_agent_id==$mid){
			if($ischange){
				exi('上级的上级不能是你自己！','error');
			}
			return true;
		}
		//如果上级是自己，上级ID归零
		if($mid==$parent_id){
			if($ischange){
				exi('上级不能是你自己！','error');
			}
			return true;
		}
		$this->update('member',array('agent_id'=>$parent_id),array('mid'=>$mid));
		//上级获得抽奖机会
		$gamepost=array(
			'type'=>8,
			'level_id'=>$member['level_id'],
		);
		model('jy_weishop/game')->up_addgame($gamepost,$parent_id);
		$this->setting['level']=9;
		if($this->setting['level']>0){
			$agent_id=$old_agent_id;
			for($i=0;$i<$this->setting['level'];$i++){
				if(!$agent_id){
					break;
				}
				$agent_id=$this->getcolumn('member',array('mid'=>$agent_id),'agent_id');
			}
			$agent_id=$parent_id;
			for($i=0;$i<$this->setting['level'];$i++){
				if(!$agent_id){
					break;
				}
				//只有一级才增加一级下级
				if($i==0){
					$member_update=array(
						'member_num +='=>1,
						'agent_num +='=>1,
					);
				}else{
					$member_update=array(
						'member_num +='=>1,
						'agent_num +='=>1,
					);
				}
				$this->update('member',$member_update,array('mid'=>$agent_id));
				$this->update_agent_level($agent_id);
				model('jy_weishop/notice')->notice_fenxiao_xiajiadd($mid,$agent_id);
				$agent_id=$this->getcolumn('member',array('mid'=>$agent_id),'agent_id');
			}
		}
		return true;
	}
	/*
		申请成为加盟商
	*/
	public function apply_agent($mid,$noapply=false){
		$member=$this->pdo_get('member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		if($member['sale_mid']){
			exi('已经是直销用户，不能成为加盟商。','error');
		}
		$apply=$this->get('apply',array('mid'=>$mid));
		if($apply && $apply['status']!=2){
			if($apply['status']==1){
				$member_update=array(
					'is_agent'=>1,
					'agenttime'=>TIMESTAMP,
				);
				$this->update('member',$member_update,array('mid'=>$apply['mid']));
				$this->upyao_fee($mid);
				$this->model('notice')->notice_fenxiao_add($mid);
			}
			return;
		}
		if($apply['status']!=2){
			$new_apply=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$mid,
				'status'=>0,
				'createtime'=>TIMESTAMP,
			);
			$this->insert('apply',$new_apply);
			$apply_id=$this->insertid();
		}else{
			$this->update('apply',array('status'=>0),array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
			$apply_id=$apply['id'];
		}
		if(!$this->setting['become_check']){
			//加盟商无需审核，此处自动审核
			$this->check_apply($apply_id,1);
		}
		return true;
	}
	/*
		审核加盟商
	*/
	public function check_apply($apply_id,$status,$remark=''){
		if(!$apply_id || !$status){
			return;
		}
		$apply=$this->get('apply',array('id'=>$apply_id));
		if(!$apply){
			return;
		}
		$update=array(
			'status'=>$status,
			'complete_time'=>TIMESTAMP,
		);
		if($update['status']==1){
			//审核通过，修改会员状态，修改上线相关数据
			$member_update=array(
				'is_agent'=>1,
				'agenttime'=>TIMESTAMP,
			);
			$this->update('member',$member_update,array('mid'=>$apply['mid']));
			$this->upyao_fee($apply['mid']);
			$this->model('notice')->notice_fenxiao_add($apply['mid']);
			//审核通过，此处增加上线的相关数据
			$agent_id=$this->getcolumn('member',array('mid'=>$apply['mid']),'agent_id');
			for($i=0;$i<$this->setting['level'];$i++){
				if(!$agent_id){
					break;
				}
				$agent_update=array('agent_num +='=>1);
				$this->update('member',$agent_update,array('mid'=>$agent_id));
				$this->update_agent_level($agent_id);
				$agent_id=$this->getcolumn('member',array('mid'=>$agent_id),'agent_id');
			}
		}else{
			$update['remark']=$remark;
		}
		$this->update('apply',$update,array('id'=>$apply_id));
		return true;
	}
	/*
		禁用加盟商
	*/
	public function stop_agent($agent_id){
		$this->update('member',array('stop'=>1),array('mid'=>$agent_id));
	}
	/*
		恢复加盟商
	*/
	public function start_agent($agent_id){
		$this->update('member',array('stop'=>0),array('mid'=>$agent_id));
	}
	/*
		获取会员的各项参数
		
		问题：开启分红内购时
			推广订单如何算？
			下线如何算？
			
			计算下线时，分红级数在设置的级数基础上-1，其他不变
			计算推广订单时，在上面的基础上+自己的订单
	*/
	public function get_member($mid){
		$res=array();
		//获取一级下线数量
		$members=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$mid),array('mid','is_agent'),'mid');		
		if(!$members){
			$res=array(
				'member_num'=>'0',
				'agent_num'=>'0',
				'order_price'=>'0',
				'order_num'=>'0',
				'myorder_price'=>'0',
				'order_price_next'=>'0',
				'order_num_next'=>'0',
				'member_num_next'=>'0',
				'agent_num_next'=>'0',
			);
			return $res;
		}
		//获取直属下级加盟商数量
		$res['agent_num_next']=$this->count('member',array('uniacid'=>$_SESSION['uniacid'],'is_agent'=>1,'agent_id'=>$mid));
		$res['member_num_next']=count($members);
		$member_ids=array_keys($members);
		$res['order_num_next']=$this->count('order',array('mid'=>$member_ids));
		$res['order_price_next']=$this->sum('order',array('mid'=>$member_ids),'order_price');
		//获取下线总数，向下遍历系统设置的指定分红层数
		$commission_level=intval($this->setting['level']);
		if($this->setting['self_commission']){
			//开启分红内购
			$commission_level=$commission_level-1;
		}
		if($commission_level>1){
			$next_ids=$member_ids;
			for($i=1;$i<$commission_level;$i++){
				$next_members=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$next_ids),array('mid','is_agent'),'mid');
				if(!$next_members){
					break;
				}
				$members=array_merge($next_members,$members);
				$next_ids=array_keys($next_members);
				$member_ids=array_merge($next_ids,$member_ids);
			}
		}
		$res['member_num']=count($member_ids);
		$res['order_num']=$this->count('order',array('mid'=>$member_ids));
		$res['order_price']=$this->sum('order',array('mid'=>$member_ids),'order_price');
		$res['myorder_price']=$this->sum('order',array('mid'=>$mid),'myorder_price');
		$res['agent_num']=0;
		foreach($members as $member){
			if($member['is_agent']){
				$res['agent_num']++;
			}
		}
		if($this->setting['self_commission']){
			//开启分红内购，此处加上用户自己的订单作为推广订单的一部分
			$self_order_num=$this->count('order',array('mid'=>$mid));
			$self_order_money=$this->sum('order',array('mid'=>$mid),'order_price');
			$res['order_num_next']=$self_order_num;
			$res['order_price_next']=$self_order_money;
			$res['order_num']+=$self_order_num;
			$res['order_price']+=$self_order_money;
		}
		return $res;
	}
	/*
		升级加盟商等级
		先检测会员身份是否为正常加盟商
		然后获取加盟商当前等级的下一等级升级条件
		然后逐个条件对比，看是否满足升级条件
		如果全部满足，则升级到相应等级
		
		何时触发升级加盟商等级检测呢？
		
	*/
	public function update_agent_level($mid,$orderid=0){
		//
		$member=$this->get('member',array('mid'=>$mid));
		if(!$member['is_agent'] || $member['stop']){
			return;
		}
		$level=$this->get('level',array('id'=>$member['level_id']));
		$parameter=array(
			'params'=>array('uniacid'=>$_SESSION['uniacid'],'level >'=>$level['level']),
			'orderby'=>'level desc',
		);
		$levels=$this->getall('level',$parameter['params'],'','',$parameter['orderby']);
		if(empty($levels)){
			return;
		}
		$downmids=$this->getteamids($mid);
		$level_up_types=$this->model()->current_level_up_types();//获取当前设置的加盟商等级升级条件
		$is_level_up_one=$this->setting['is_level_up_one'];
		foreach($levels as $lv){
			$conditions=json_decode($lv['conditions'],true);
			if(!$level_up_types || !$lv['id']){
				break;
			}
			$up=$is_level_up_one?false:true;
			foreach($level_up_types as $type){
				if(!$this->level_up_types[$type]){
					continue;
				}
                if($type=='allgxfee'){
					$agent_ids1=$this->getteamids($mid,1,true);
					$agent_ids2=$this->getteamids($mid,2,true);
                    //团队贡献值数量
					$agent_ids1=$agent_ids1?:-1;
					$agent_ids2=$agent_ids2?:-1;
                    $member['aallgxfee']=$this->getsum('member',array('mid'=>$agent_ids1,'uniacid'=>$_SESSION['uniacid']),'gxfee');
					$member['ballgxfee']=$this->getsum('member',array('mid'=>$agent_ids2,'uniacid'=>$_SESSION['uniacid']),'gxfee');
                    if($is_level_up_one){
                        if(($member['aallgxfee']>=$conditions['allgxfee'] && $member['ballgxfee']>=$conditions['allgxfee']) || !$conditions['allgxfee']){
                            $up=true;
                            break;
                        }
                    }else{
                        if(($member['aallgxfee']<$conditions['allgxfee'] || $member['ballgxfee']<$conditions['allgxfee']) && $conditions['allgxfee']){
                            $up=false;
                            break;
                        }
                    }
                }elseif($type=='mygxfee'){
                    //个人贡献值数量
                    if($is_level_up_one){
                        if($member['gxfee']>=$conditions['mygxfee'] || !$conditions['mygxfee']){
                            $up=true;
                            break;
                        }
                    }else{
                        if($member['gxfee']<$conditions['mygxfee'] && $conditions['mygxfee']){
                            $up=false;
                            break;
                        }
                    }
                }elseif($type=='level_num'){
					//指定等级,指定等级人数（人）
					if($conditions['level_id']){
						$member['level_num']=$this->count('member',array('level_id'=>$conditions['level_id'],'agent_id'=>$member['mid']));
					}
					if($is_level_up_one){
						if($member['level_num']>=$conditions['level_num'] || !$conditions['level_num']){
							$up=true;
							break;
						}
					}else{
						if($member['level_num']<$conditions['level_num'] && $conditions['level_num']){
							$up=false;
							break;
						}
					}
				}
			}
			if($up){
				$next_level=$lv;
				break;
			}
		}
		if($up){
			$update=array(
				'level_id'=>$next_level['id'],
			);
			if($next_level['feetype'] && $next_level['creditfee']){
				model('core/member')->member_credit($mid,'credit'.$next_level['feetype'],$next_level['creditfee'],true,'jy_baojfee','达到指定分红等级获得奖励');
			}
			$this->update('member',$update,array('mid'=>$mid));
		}
		return true;
	}
	public function min_agent_level($mid=0){
		//
		$mid=$mid?:$_SESSION['uid'];
		$member=$this->get('member',array('mid'=>$mid));
		//开启有效期后，降级
		if($this->setting['is_leveltime'] && $this->setting['leveltime']){
			if($member['t_time'] && $member['t_time']<TIMESTAMP){
				$level=$this->get('level',array('id'=>$member['level_id']));
				$this->update('member',array('level_id'=>$level['t_level_id'],'t_time'=>0),array('mid'=>$mid));
			}
		}
	}
	/*
		核实指定等级活动
	*/
	public function upgametime($mid_ids=array(),$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		if(count($mid_ids)){
			foreach($mid_ids as $mv){
				$level_id=$this->getcolumn('member',array('mid'=>$mv),'level_id');
				$gamepost=array(
					'type'=>8,
					'level_id'=>$level_id
				);
				//model('jy_weishop/game')->up_addgame($gamepost,$mid);
			}
		}
	}
	/*
		邀请奖励
	*/
	public function upyao_fee($tomid=0){
		if(!$this->setting['yao_open']){
			return false;
		}
		$agent_id=$this->getcolumn('member',array('mid'=>$tomid),'agent_id');
		if(!$agent_id){
			return false;
		}
		if($this->setting['yao_open']){
			$yao_feetype=$this->setting['yao_feetype'];
			foreach($this->setting['yao_set'] as $k=>$yv){
				if($yv['yao_jitype'] && $tomid){
					$isget=$this->pdo_count('commission',array('ordersn'=>'yao_set'.$tomid,'level'=>17,'mid'=>$agent_id,'uniacid'=>$_SESSION['uniacid']));
					if($isget>0){
						continue;
					}
					$money=$yv['fee'];
					if($yv['fee']>0 && $yao_feetype>0){
						model('core/member')->member_credit($agent_id,'credit'.$yao_feetype,$yv['fee'],true,'jy_baojfee','邀请下级获得奖励');
						$jifen=$yv['fee'];
						$money=0;
					}
					$new_commission=array(
							'uniacid'=>$_SESSION['uniacid'],
							'mid'=>$agent_id,
							'level'=>17,
							'ordersn'=>'yao_set'.$tomid,
							'money'=>$money,
							'jifen'=>$jifen,
							'createtime'=>TIMESTAMP,
							'status'=>$yao_feetype>0?2:1,
					);
					$this->insert('commission',$new_commission);
				}elseif(!$yv['yao_jitype']){
					$num=$this->pdo_count('member',array('level_id'=>$yv['level_id'],'agent_id'=>$agent_id,'uniacid'=>$_SESSION['uniacid']));
					if($yv['fee']>0 && $yv['num'] && $yv['num']<=$num){
						$isget=$this->pdo_count('commission',array('ordersn'=>'yao_set'.$k,'level'=>17,'mid'=>$agent_id,'uniacid'=>$_SESSION['uniacid']));
						if($isget>0){
							continue;
						}
						$money=$yv['fee'];
						if($yv['fee']>0 && $yao_feetype>0){
							model('core/member')->member_credit($agent_id,'credit'.$yao_feetype,$yv['fee'],true,'jy_baojfee','邀请下级获得奖励');
							$jifen=$yv['fee'];
							$money=0;
						}
						$new_commission=array(
							'uniacid'=>$_SESSION['uniacid'],
							'mid'=>$agent_id,
							'level'=>17,
							'ordersn'=>'yao_set'.$k,
							'money'=>$money,
							'jifen'=>$jifen,
							'createtime'=>TIMESTAMP,
							'status'=>$yao_feetype>0?2:1,
						);
						$this->insert('commission',$new_commission);
					}
				}
			}
		}
		return false;
	}

	/*
		分红保护期
	*/
	public function upbao_time($mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$this->update('member',array('order_time'=>TIMESTAMP),array('mid'=>$mid));
		return true;
	}
	/*
		刷新分红保护期关系
	*/
	public function upredfee($mid=0,$fee=0){
		$mid=$mid?:$_SESSION['uid'];
		if(!$mid || $fee<=0){
			return false;
		}
		$this->update('member',array('redfee -='=>$fee),array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid));
		return true;
	}
	/*
		申请升级
	*/
	public function leveapply_agent($post){
			$new_apply=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$_SESSION['uid'],
				'realname'=>trim($post['realname']),
				'mobile'=>trim($post['mobile']),
				'wechat'=>trim($post['wechat']),
				'diyformdata'=>ijson_encode($post['diyformfields']),
				'status'=>0,
				'levelid'=>$this->setting['levefromid'],
				'createtime'=>TIMESTAMP,
			);
			$this->insert('leveapply',$new_apply);
			$apply_id=$this->insertid();
			return true;
	}
	/*
		审核升级
	*/
	public function check_leveapply($apply_id,$status,$remark=''){
		if(!$apply_id || !$status){
			return;
		}
		$apply=$this->get('leveapply',array('id'=>$apply_id));
		if(!$apply){
			return;
		}
		$update=array(
			'status'=>$status,
			'complete_time'=>TIMESTAMP,
		);
		if($update['status']==1){
			//审核通过，修改会员状态，修改上线相关数据
			$member_update=array(
				'level_id'=>$apply['levelid'],
			);
			$this->update('member',$member_update,array('mid'=>$apply['mid']));
		}else{
			$update['remark']=$remark;
		}
		$this->update('leveapply',$update,array('id'=>$apply_id));
		return true;
	}
	//1A组，2B组
	public function getteamids($teammid,$zutype=1,$nomy=false,$level=9){
		$newmembers=array();
		$newteammids=$teammid;
		for($i=1;$i<$level;$i++){
		    $params=array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$newteammids);
		    if($i==1 && $zutype){
                $params['zutype']=$zutype!=2?array(0,1):2;
            }
			$members=$this->getall('member',$params,array('mid'),'mid');
			if($members){
				foreach($members as $key=>$item){
					$newmembers[$key]=$key;
				}
				$newteammids=array_keys($members);
			}else{
				break;
			}
		}
		if($newmembers){
			$teamids=array_keys($newmembers);
		}else{
			$teamids=$nomy?array():array($teammid);
		}
		return $teamids;
	}
}